<template>
  <van-form >
    <van-cell-group inset>
      <van-field
          v-model="form.name"
          name="名称"
          label="名称"
          placeholder="请输入名称"
          :rules="[{ required: true, message: '请填写名称' }]"
      />
      <van-field
          v-model="result"
          is-link
          readonly
          name="picker"
          label="类型"
          placeholder="点击选择类型"
          @click="showPicker = true"
      >
        <template #input v-if="form.type[0]">
          <van-tag
              plain
              type="primary"
              v-for="(item, index) in form.type"
              :key="index"
              :color="item.color"
              style="margin-right: 10px"
              closeable
          >{{ item.text }}
          </van-tag
          >
        </template>
      </van-field>

      <van-popup v-model:show="showPicker" position="bottom">
        <van-picker
            :columns="jobTypeList"
            @confirm="onConfirm"
            @cancel="showPicker = false"
        />
      </van-popup>


      <van-field
          label="成本"
          :model-value="form.price"
          placeholder="点击输入成本"
          readonly
          clickable
          @touchstart.stop="show = true"
      />
      <van-number-keyboard
          :show="show"
          @blur="show = false"
          v-model="form.price"
      />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit" @click="handleSubmit">
        提交
      </van-button>
    </div>
  </van-form>
</template>
<script setup lang="ts" name="Home">
import {ref} from "vue";
import {showNotify} from "vant";
import {useResetReactive} from "../../hooks";
import park from '../../api/park.ts'
import {getTypeList} from "../../api/manage.ts";
import {router} from "../../router";
const [form, resetForm] = useResetReactive({
  name: "",
  price: '',
  type:[] as any
});
resetForm();
const show = ref(false);
const result = ref("");
const showPicker = ref(false);
const jobTypeList = ref([]);

function reloadTypeList(){
  getTypeList(1).then(res=>{
    jobTypeList.value = JSON.parse(JSON.stringify(res).replace(/id/g,'value').replace(/name/g,'text'))
  })
}
reloadTypeList()
function listToString(data){
  let arr = []
  data.map(x=>arr.push(x.value))
  return arr.toString();
}
function stringToList(str,options){
  const arr = str.split(',')
  return  arr.map(x=> options.find(z=>z.value === x))
}
function setToArr(arr,data){
  const r = arr.find(x=>(x.value === data[0].value))
  if(!r){
    arr.push(data[0])
  }
}
const onConfirm = ({selectedOptions}) => {
  setToArr(form.type,selectedOptions)
  showPicker.value = false;
};

function handleSubmit() {
  const data = {
    type: listToString(form.type),
    name:form.name,
    price: form.price,
  }
  park.insert(data).then(res=>{
    showNotify({type: "success", message: "新增成功"});
    router.push({path:'/park'})
  })
}
</script>
